import db from './mysqlHelper.js';
import moment from 'moment';
import schedule from 'node-schedule';
import { DEVICES } from "./publicValue.js";



async function test(){
    console.log("每小时统计数据启动")
    DEVICES.set('636f6d33017000000005`', {sn:'636f6d33017000000005',last_activivty:moment()});
    let sqls=[];
    for(const key of DEVICES.keys()){
        let device = DEVICES.get(key);
        let now = moment();
         now=now.subtract(1, 'hours');
        console.log('now:',now.format('YYYY-MM-DD HH:mm:ss'));  
        let startTime = now.format('YYYY-MM-DD HH:00:00');
        let endTime =now.format('YYYY-MM-DD HH:59:59');
        let startRecord=await db.findAllNoPage('history',{sn:device.sn},'read_time','asc',1,0,[{field:'read_time',start:startTime,end:endTime}]);
        let endRecord=await db.findAllNoPage('history',{sn:device.sn},'read_time','desc',1,0,[{field:'read_time',start:startTime,end:endTime}]);
        if(startRecord.length==0||endRecord.length==0){
            console.log(device.sn, '缺少历史数据取消用量统计');
            break;
        }
        else{
            let used={
                sn:device.sn,
                write_time:moment().format('YYYY-MM-DD HH:00:00'),
                start_time:startRecord[0].read_time,
                end_time:endRecord[0].read_time,
                start_value:startRecord[0].total_flow,
                end_value:endRecord[0].total_flow,
                total:endRecord[0].total_flow-startRecord[0].total_flow
            }
            sqls.push({sql:`INSERT INTO used SET ?`,param:[used]});
        }
        
    }
    if(sqls.length>0){
        let res = await db.transaction(sqls);
        if (res instanceof Error) {
            console.error('每小时统计数据写入失败', res.message,JSON.stringify(sqls));
            return;
        }
        console.log(`每小时统计数据写入成功`);
    }
    
}

test();